const db = require('../db/index')


// 获取所有专业信息
exports.getMajorInfo = (req, res) => {      
    const sql = 'select * from majors where isdelete = 0'
    db.query(sql, (err, result) => {
        if(err) return res.show(err)
        if(result.length === 0) return res.show("专业信息查询失败！")
        res.send({
            status: 0,
            message: "查询成功！",
            data: result
        })
        
    })

}

// 更新
exports.updateMajorInfo = (req, res) => {
    const sql = 'update majors set ? where majorId = ?'
    db.query(sql, [req.body, req.body.majorId], (err, result) => {
        if(err) return res.show(err)
        if(result.affectedRows !== 1) return res.show("更新专业信息失败！")
        res.show("更新专业信息成功！", 0)
    })
}


// 新增
exports.addMajor = (req, res) => {
    const sql = 'select * from majors where majorName = ? or engName = ?'
    db.query(sql, [req.body.majorName, req.body.engName], (err, result) => {
        if(err) return res.show(err)
        if(result.length === 2) return res.show('专业名称与别名被占用，请更换后重试！')
        if (results.length === 1 && results[0].majorName === req.body.majorName && results[0].engName === req.body.engName) return res.show('分类名称与别名被占用，请更换后重试！')
        // 分类名称 或 分类别名 被占用
        if (results.length === 1 && results[0].majorName === req.body.majorName) return res.show('专业名称被占用，请更换后重试！')
        if (results.length === 1 && results[0].engName === req.body.engName) return res.show('专业别名被占用，请更换后重试！')

        const sql = 'insert into majors set ?'
        db.query(sql, 
            {category: req.body.category, majorName: req.body.majorName, engName: req.body.engName}, 
            (err, result) => {
            if(err) return res.show(err)
            if(result.affectedRows !== 1) return res.show("新增专业失败！")
            res.show("新增专业成功！", 0)
        })
    })
    
}



// 删除
exports.deleteMajor = (req, res) => {
    // const sql = 'delete from majors where majorId = ?'
    const sql = 'update majors set isdelete = 1 where majorId = ?'
    db.query(sql, req.params.id, (err, result) => {
        if(err) return res.show(err)
        if(result.affectedRows !== 1) return res.show("删除专业失败！")
        res.show("删除成功！", 0)
    })
}